const path = require('path');
const fs = require('fs');

const {randomFileName} = require('./../utils/fs-extend')
const {uploadByFile, uploadByStream} = require('./../utils/upload')
const {Response, ResponseError} = require('./../utils/Response') //引入响应类
const {CODE, STATUS}  = require('./../utils/RES_CODE') 
module.exports = {
  /* 流模式 */

  //上传单个
  async uploadOneFileByStream(uploadPath) {
    //获取文件流
    const stream = await this.getFileStream();
    return [await uploadByStream(stream, uploadPath), stream.fields]
  },

  //上传多个
  async uploadMultiFileByStream(uploadPath) {
    const filesInfo = this.multipart();
    let part;
    const fileInfoArr = []
    const fields = {}
    // parts() 返回 promise 对象
    while((part = await filesInfo()) != null) {
      if(Array.isArray(part)) { //其他字段
        fields[part['0']] = part['1']
      }else { //流
        const stream = part
        const fileInfo = await uploadByStream(stream, uploadPath)
        fileInfoArr.push(fileInfo)
      }
    }
    return [fileInfoArr, fields]
  },
  
  /* 文件模式 */

  //上传单个
  uploadOneFileByFile(uploadPath) {
    const fileInfo = this.request.files[0]          //获取文件对象来源
    this.cleanupRequestFiles()
    return uploadByFile(fileInfo, uploadPath)
  },

  //上传多个
  uploadMultiFileByFile(uploadPath) {
    const filesInfo = this.request.files
    const fileInfoArr = []
    for(let fileInfo of filesInfo) {
      fileInfoArr.push(uploadByFile(fileInfo, uploadPath))
    }
    this.cleanupRequestFiles()
    return fileInfoArr
  },

  
  //随机的文件名称
  randomFileName,
  //响应的工具对象
  Response,
  ResponseError,
  CODE,
  STATUS
}